<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文章 - StudentHub</title>
    <link rel="shortcut icon" href="/public/favicon.ico" type="image/x-icon">
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- 引入 wangEditor -->
    <script src="https://unpkg.com/wangeditor@4.7.15/dist/wangEditor.min.js"></script>

    <!-- 配置 Tailwind (Optional, copy from user-center.html if needed) -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36D399',
                        neutral: {
                            100: '#F8FAFC',
                            200: '#E2E8F0',
                            300: '#CBD5E1',
                            400: '#94A3B8',
                            500: '#64748B',
                            600: '#475569',
                            700: '#334155',
                            800: '#1E293B',
                            900: '#0F172A',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.03)',
                        'card-hover': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        /* Add any specific styles for this page here */
    </style>
</head>
<body class="font-inter bg-neutral-100 text-neutral-800">
    <!-- 导航栏 (Optional, copy from user-center.html if needed) -->
    <header class="sticky top-0 z-50 bg-white shadow-sm">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <a href="/qian/home.html" class="text-primary font-bold text-xl">StudentHub</a>
            <!-- Navigation links -->
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8 md:py-12">
        <div class="bg-white rounded-2xl shadow-card p-6 md:p-8">
            <h1 class="text-2xl font-bold text-neutral-900 mb-6">编辑文章</h1>

            <form id="editArticleForm">
                <div class="mb-4">
                    <label for="articleTitle" class="block text-sm font-medium text-neutral-700 mb-2">文章标题</label>
                    <input type="text" id="articleTitle" name="title" class="form-control block w-full rounded-md border-neutral-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30" placeholder="输入文章标题">
                </div>

                <div class="mb-4">
                    <label for="articleContent" class="block text-sm font-medium text-neutral-700 mb-2">文章内容</label>
                    <div id="editor" class="form-control block w-full rounded-md border-neutral-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30" style="min-height: 300px;"></div>
                </div>

                <div class="mb-4">
                    <label for="articleCategory" class="block text-sm font-medium text-neutral-700 mb-2">文章标签</label>
                    <select id="articleCategory" name="articleCategory" class="form-control block w-full rounded-md border-neutral-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30">
                        <option value="">请选择标签</option>
                    </select>
                </div>

                <div class="mb-4">
                    <label for="articleStatus" class="block text-sm font-medium text-neutral-700 mb-2">文章状态</label>
                    <select id="articleStatus" name="status" class="form-control block w-full rounded-md border-neutral-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30">
                        <option value="1">已发布</option>
                        <option value="0">草稿</option>
                    </select>
                </div>

                <!-- Add more fields as needed, e.g., tags, category -->

                <div class="flex justify-end mt-6">
                    <button type="submit" id="saveArticleChangesBtn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg font-medium transition-colors">
                        保存修改
                    </button>
                     <a href="/qian/user-center.html" class="ml-4 bg-neutral-300 hover:bg-neutral-400 text-neutral-800 px-6 py-2 rounded-lg font-medium transition-colors flex items-center justify-center">
                       取消
                     </a>
                </div>
            </form>
        </div>
    </main>

    <!-- 底部区域 (Optional, copy from user-center.html if needed) -->
    <footer class="bg-white border-t border-neutral-200 mt-12">
        <div class="container mx-auto px-4 py-8">
            <!-- Footer content -->
        </div>
    </footer>

    <script src="/jquery-3.7.1.min.js"></script>
    <script>
        let editor; // Declare editor variable globally or in a scope accessible by init and submit

        $(document).ready(function() {
            // Check if wangEditor is loaded successfully
            if (typeof window.wangEditor === 'undefined') {
                console.error('wangEditor 加载失败');
                alert('编辑器加载失败，请刷新页面重试');
                return;
            }

            try {
                // Initialize wangEditor
                const E = window.wangEditor;
                editor = new E('#editor');

                // Configure editor
                editor.config.height = 300;
                editor.config.placeholder = '在这里撰写你的文章内容';
                editor.config.zIndex = 1;

                // Configure image upload
                editor.config.uploadImgServer = 'http://localhost:8082/api/upload/editorImage';
                editor.config.uploadFileName = 'editorImage';
                editor.config.uploadImgMaxSize = 5 * 1024 * 1024; // 5MB

                // Configure image upload callback
                editor.config.uploadImgHooks = {
                    customInsert: function(insertImgFn, result) {
                        // result is the server's response
                        if (result.errno === 0) {
                            // Get image URL from the returned data
                            const url = result.data.url;
                            insertImgFn(url);
                        } else {
                            alert('图片上传失败：' + (result.message || '未知错误'));
                        }
                    }
                };

                // Create editor
                editor.create();

                // Add error handling
                editor.config.onerror = function (err) {
                    console.error('编辑器错误:', err);
                    alert('编辑器发生错误，请刷新页面重试');
                };
            } catch (e) {
                console.error('wangEditor 初始化失败:', e);
                alert('编辑器初始化失败，请检查控制台错误。');
                return;
            }

            const urlParams = new URLSearchParams(window.location.search);
            const articleId = urlParams.get('articleId');

            // 先获取类别列表 (原 fetchTags) 
            function fetchCategories(selectedArticleTagId) { // 接收标签ID
                console.log('fetchCategories called', selectedArticleTagId);
                $.ajax({
                    url: 'http://localhost:8082/api/tags/',
                    method: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        console.log('API /api/tags/ response data:', data);
                        if (data.code === 200 && Array.isArray(data.data)) {
                            var categorySelect = $('#articleCategory');
                            categorySelect.empty();
                            categorySelect.append('<option value="">请选择标签</option>');
                            
                            let selectedTagName = '';
                            data.data.forEach(function(tag) {
                                categorySelect.append('<option value="' + tag.id + '">' + tag.name + '</option>'); // 使用 tag.id 作为 value，tag.name 作为显示文本
                                if (selectedArticleTagId && tag.id === selectedArticleTagId) {
                                    selectedTagName = tag.name;
                                }
                            });
                            
                            if (selectedTagName) {
                                categorySelect.val(String(selectedArticleTagId)); // 选中对应的标签ID
                            }
                        } else {
                            alert('获取标签数据失败');
                        }
                    },
                    error: function() {
                        alert('无法连接到标签接口');
                    }
                });
            }

            if (articleId) {
                // 先获取文章数据，再渲染类别下拉框并选中
                $.ajax({
                    url: `http://localhost:8082/api/articles/${articleId}`,
                    type: 'GET',
                    success: function(response) {
                        if (response && response.data) {
                            const article = response.data;
                            $('#articleTitle').val(article.title);
                            if (editor) {
                                editor.txt.html(article.content);
                            }
                            fetchCategories(article.tagId); // 传入标签ID
                            $('#articleStatus').val(String(article.status)); // 设置文章状态
                        } else {
                            alert('获取文章数据失败，请检查API响应。');
                        }
                    },
                    error: function() {
                        alert('无法加载文章数据，请稍后重试。');
                    }
                });
            } else {
                fetchCategories(); // 新建时只渲染下拉
                alert('无法编辑文章：缺少文章ID。');
                window.location.href = '/qian/user-center.html';
            }

            // Handle form submission
            // 移除这里的 on('submit')，因为我们将通过按钮的 click 事件来处理
            // $('#editArticleForm').on('submit', function(e) {
            //     e.preventDefault();
            //     console.log('Form submit event triggered!');
            //     return false;
            // });

            // 为保存按钮添加点击事件
            $('#saveArticleChangesBtn').on('click', function(e) {
                e.preventDefault(); // 阻止按钮的默认行为（包括表单提交）
                console.log('Save button clicked!'); // 打印点击事件触发信息

                const updatedArticleData = {
                    id: articleId, // Include the article ID
                    title: $('#articleTitle').val(),
                    content: editor.txt.html(), // Get content from wangEditor
                    tagId: $('#articleCategory').val(), // 将 tagName 修改为 tagId
                    status: $('#articleStatus').val() // Get article status
                };

                console.log('updatedArticleData:', updatedArticleData);

                // Example update (replace with your actual API call):
                $.ajax({
                    url: `http://localhost:8082/api/articles/edit`,
                    type: 'PUT', // Use PUT for editing
                    contentType: 'application/json',
                    data: JSON.stringify(updatedArticleData),
                    success: function(response) {
                        if(response && response.code === 200) { // Assuming success indicates code 200
                             alert('文章保存成功！');
                            // Optionally redirect back to user center or article detail page
                            window.location.href = `/qian/user-center.html`; // Redirect on success
                        } else {
                             console.error('保存文章失败:', response);
                             alert('保存文章失败：' + (response.message || '未知错误'));
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error saving article:', error);
                        alert('保存文章失败，请稍后重试。');
                    }
                });
            });
            
        });
    </script>
</body>
</html> 